package com.lkd.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dto.SkuClassDto;
import com.lkd.entity.Sku;
import com.lkd.entity.SkuClass;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.SkuClassMapper;
import com.lkd.service.ISkuClassService;
import com.lkd.service.ISkuService;
import com.lkd.vo.PageBean;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品类别表 服务实现类
 * </p>
 *
 * @author xiaotao
 * @since 2025-10-09
 */
@Service
@RequiredArgsConstructor
public class SkuClassServiceImpl extends ServiceImpl<SkuClassMapper, SkuClass> implements ISkuClassService {

    /**
     * 分类搜索
     *
     * @param skuClassDto
     * @return
     */
    private final ISkuService skuService;
    @Override
    public PageBean<SkuClass> search(SkuClassDto skuClassDto) {
        //1.设置分页参数
        Page<SkuClass> skuClassPage = new Page<>(skuClassDto.getPageIndex(), skuClassDto.getPageSize());

        //2.设置业务参数
        LambdaQueryWrapper<SkuClass> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(skuClassDto.getClassName()), SkuClass::getClassName, skuClassDto.getClassName());

        //3.执行分页查询
        Page<SkuClass> page = this.page(skuClassPage, wrapper);

        //4.构建返回结果
        return new PageBean<>(page);
    }

    /**
     * 删除商品类别
     *
     * @param classId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer classId) {
        //1.查看该类别下是否有sku
        long skuCount = skuService.lambdaQuery().
                eq(Sku::getClassId, classId)
                .count();

        if(skuCount > 0){
            throw new BusinessException("该商品类别下仍然有商品，无法删除");
        }else{
            //没有关联数据，可以直接删除该商品类别
            removeById(classId);
        }
    }
}
